package com.epoint.mobileoa.service;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.bizlogic.FrameParam;
import com.epoint.mobileoa.bizlogic.NewTask;
import com.epoint.mobileoa.bizlogic.SkipFlag;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.exception.CrashHandler;
import com.epoint.mobileoa.exception.ExceptionMsg;
import com.epoint.mobileoa.http.HttpHelp;
import com.epoint.mobileoa.tools.HttpUtil;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.MusicHelp;
import com.epoint.mobileoa.tools.PhoneHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.ui.login.LoginView;
import com.epoint.mobileoa.ui.mail.MailBoxReceiveView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author liyc
 * @time 2012-1-16 下午9:44:50
 * @annotation 后台服务,任务执行引擎，异常处理引擎
 */
public class MainService extends Service{

	public static final String Name = "com.epoint.mobileoa.service.MainService";

	public static boolean isrun1;

	public static boolean isNetCheck;

	public static FrameParam fp;// 全局变量

	public static final String TaskAction = "new_epointmessage_receiver";

	private static String EXCEPTION_MSG = ExceptionMsg.TASK_DO_ERR;

	//	public static int NetBreakFlag;//断网标记

	public static boolean NetIsOk;//网络是否通畅

	public int checkNetTime = 15*1000;//检查网络时间间隔

	public int doTaskTime = 1*1000;//每做一次任务间隔时间

	public static int lastallmailnums;//所有邮件数量

	public static int lastallarchivenums;//所有公文数量

	public static String NORMAL = "normal";//数据状态正常标准

	public static String ERROR= "error";//数据状态异常

	public static Thread netcheckThread;//网络监测线程

	private Thread taskExecuteThread;//任务执行线程

	private Thread newTaskExecuteThread;

	private static int CheckNetTimeOutTimesBreak = 3;//累计检测网络异常次数

	public static int newgetmailnums,newgetarchivenums;

	public static int MAIL_NOTIFICATION_FLAG = 1;//邮件状态栏标识

	public static int ARCHIVE_NOTIFICATION_FLAG = 2;//待办状态栏标识

	public static List<Task> allTask = new ArrayList<Task>();//存储所有的任务

	public static List<NewTask> allNewTask = new ArrayList<NewTask>();//所有新任务

	public static void addNewTask(NewTask newTask) {
		allNewTask.add(newTask);
	}

	/**
	 * 更新UI
	 */
	private Handler hand = new Handler() {

		@Override
		public void handleMessage(Message mess) {
			SuperView sv = null;
			try{
				if(mess.arg1==-100){
					ToastHelp.sendBroadcastToast(getApplicationContext(), EXCEPTION_MSG, 0);
					EXCEPTION_MSG = ExceptionMsg.TASK_DO_ERR;
					sv = (SuperView) mess.obj;
					sv.refresh(ERROR);
				}
				else if(mess.arg1==1){
					HashMap<String, Object> map = (HashMap<String, Object>) mess.obj;
					sv = (SuperView) map.get("context");
					Object data = map.get("data");
					catachRefreshUIException(sv,data);
				}
				else{
					ToastHelp.sendBroadcastToast(getApplicationContext(), ExceptionMsg.APP_EXECTUE_ERR, 0);
				}
			}catch(Exception e){

				if(sv!=null){
					sv.finish();
				}

				ToastHelp.sendBroadcastToast(getApplicationContext(), ExceptionMsg.UI_REFRESH_ERR, 0);
			}
		}
	};

	private Handler newTaskhand = new Handler(){
		public void handleMessage(Message msg) {
			SuperView sv = null;
			if(msg.arg1==1){
				try{
					HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
					sv = (SuperView) map.get("context");
					Object data = map.get("data");
					int taskid = (Integer) map.get("taskId");
					System.out.println("当前新任务数："+allNewTask.size());
					sv.executeRefresh(taskid,data);
					//					allNewTask.remove(0);
				}catch(Exception e)
				{
					sendErrorMessageToast(e);
				}
			}
		};
	};

	private void sendErrorMessageToast(Exception e)
	{
		Intent intent = new Intent(getString(R.string.receiverToastActionName));
		intent.putExtra("msg", e.getMessage());
		sendBroadcast(intent);
	}

	private void catachRefreshUIException(SuperView sv,Object data){
		try{
			sv.refresh(NORMAL,data);
		}catch(Exception e){
			sv.finish();
			ToastHelp.sendBroadcastToast(this, ExceptionMsg.UI_REFRESH_ERR, 0);
		}
	}


	public void doTask(Task task) {

		Message mess = hand.obtainMessage();
		mess.arg1 = 1;
		try{
			task.exectue(mess);
		}catch (Exception e) {
			if(!EXCEPTION_MSG.equals(ExceptionMsg.CONNECT_TIME_OUT_ERR)){
			}
			mess.arg1 = -100;
			mess.obj = task.getCon();
		}
		finally{
			hand.sendMessage(mess);
			allTask.remove(task);
		}
	}

	private void doNewTask(NewTask task){
		Message mess = newTaskhand.obtainMessage();
		try {
			mess.arg1 = 1;
			task.exectue(mess);
			newTaskhand.sendMessage(mess);
		} catch (Exception e) {
			mess.arg1 = -1;
			task.getSv().finish();
		}
		finally{
			allNewTask.remove(task);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public static void addTask(Task task) {

		allTask.add(task);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//程序溃异常处理
		CrashHandler crashHandler = CrashHandler.getInstance();  
		crashHandler.init(this);
		isrun1 = true;

		NetIsOk = true;

		fp = (FrameParam) getApplication();

		//任务执行线程
		taskExecuteThread = new Thread(){
			@Override
			public void run() {
				while (isrun1) {
					synchronized (allTask) {

						if (allTask.size() > 0) {
							doTask(allTask.get(0));
						}
					}

					try {
						Thread.sleep(doTaskTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};

		taskExecuteThread.start();

		//新任务执行线程
		newTaskExecuteThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (isrun1) {
					synchronized (allNewTask) {

						if (allNewTask.size() > 0) {
							doNewTask(allNewTask.get(0));
						}
					}
					try {
						Thread.sleep(doTaskTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		newTaskExecuteThread.start();

		//网络监测
		netcheckThread = new Thread(){
			public void run() {
				while(isrun1){
					try{
						if(isNetCheck){
							String seamurl = fp.getSeamurl()+"?requestType=CheckConnectionAndGetInfo&userguid="+fp.getUserguid();
							String bs = HttpHelp.getHttpBackWithNOCheck(seamurl);

							if(!bs.contains(HttpHelp.RESPONSEINFO_SUCCESS)){/*
								NetBreakFlag++;

								LogHelp.LogI("断网标记"+NetBreakFlag);

								checkNetTime = 1*1000;

								if(NetBreakFlag>=CheckNetTimeOutTimesBreak){
									NetIsOk = false;
									MainView.updateNameThread.interrupt();
								}

								if(NetBreakFlag>=CheckNetTimeOutTimesBreak&&NetBreakFlag<CheckNetTimeOutTimesBreak+10){
									ToastHelp.sendBroadcastToast(getApplicationContext(), "网络连接异常，您已处于离线状态！", 0);
								}

							 */}
							else{
								newgetmailnums = Integer.parseInt(StringHelp.getXMLAtt(bs, "allmailnums"));

								int mailcha = newgetmailnums-lastallmailnums;
								if(mailcha>0){
									ToastHelp.sendBroadcastToast(getApplicationContext(),"收到新邮件！",R.drawable.view_folder_unread);
									showMailNotification(newgetmailnums);
								}

								newgetarchivenums = Integer.parseInt(StringHelp.getXMLAtt(bs, "allarchivenums"));


								int archivecha = newgetarchivenums-lastallarchivenums;
								if(archivecha>0){
                                   if(DBHelp.getConfigValue(getApplication(), ConfigKey.noticeMusic).equals("1")){
									MusicHelp.playMusic(MainService.this, "noticemusic.mid");
//                                       MusicHelp.playMusic(MainService.this, "task.mid");
                                   }
									ToastHelp.sendBroadcastToast(getApplicationContext(), "收到待办事宜！",R.drawable.epoint2);
								}
								lastallarchivenums = newgetarchivenums;
								lastallmailnums = newgetmailnums;

								/*if(NetBreakFlag>=CheckNetTimeOutTimesBreak){
									ToastHelp.sendBroadcastToast(getApplicationContext(), "网络恢复正常！", 0);
									MainView.updateNameThread.interrupt();
									MusicHelp.playMusic(MainService.this, "c_success.mid");
								}*/

								checkNetTime = 15*1000;
								//								NetBreakFlag = 0;
								NetIsOk = true;
							}
						}
						try {
							sleep(checkNetTime);
						} catch (InterruptedException e) {
							LogHelp.LogI("网络监测线程休眠中断！");
						}
					}catch(Exception e){
						e.printStackTrace();
						ToastHelp.sendBroadcastToast(getApplicationContext(), ExceptionMsg.NET_CHECK_ERR, 0);
					}
				}
			}
		};

		netcheckThread.start();

		String changeLoginStatus = PropertiesHelp.getProperty(this, "changeLoginStatus");
		if(changeLoginStatus.equals("1")){
			new Thread(){
				public void run() {
					while(isrefreshloginstatus){
						try {
							sleep(1000*60);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						if(isrefreshloginstatusflag){
							try{
								String seamurl = fp.generateUrl("ChangeLoginStatus",fp.getUserguid(),PhoneHelp.getDeviceId(MainService.this));
								String bs = HttpHelp.getHttpBackWithNOCheck(seamurl);

								if(bs.equals("LOGIN_STATUS_UPDATED")){
									LogHelp.LogI("登陆状态更新成功");
								}
								else if(bs.equals("ANOTHER_DEVICE_LOGIN")){
									if(PropertiesHelp.getProperty(MainService.this, "singleDeviceLogin").equals("1")){
										Intent callIntent = new Intent(Intent.ACTION_CALL);
										callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										callIntent.setClass(MainService.this, LoginView.class);
										callIntent.putExtra(SkipFlag.SKIP_TAG, SkipFlag.MAINSERVICE_ANOTHER_LOGIN_FLAG);
										startActivity(callIntent);
									}
								}
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}
				}
			}.start();
		}
	}

	protected void showMailNotification(int mailcount) {
		NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

		CharSequence from = getString(R.string.prjname);
		CharSequence message = "您当前有"+mailcount+"封未读邮件！";

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MailBoxReceiveView.class), 0);

		String tickerText = getString(R.string.prjname)+"--邮件提示";

		Notification notif = new Notification(R.drawable.epoint2, tickerText,
				System.currentTimeMillis());

        if(DBHelp.getConfigValue(getApplication(), ConfigKey.noticeMusic).equals("1")){
		notif.defaults = Notification.DEFAULT_SOUND;
        }
		notif.setLatestEventInfo(this, from, message, contentIntent);

//		notif.vibrate = new long[] { 100, 250, 100, 500};
		nm.notify(MAIL_NOTIFICATION_FLAG, notif);
	}

	public static boolean isrefreshloginstatus = true;
	public static boolean isrefreshloginstatusflag = false;

	@Override
	public void onDestroy() {
		super.onDestroy();
		LogHelp.LogI("后台服务线程销毁！");
		isrun1 = false;
		isrefreshloginstatus = false;
	}

	public static void check_bs(String bs) throws Exception{
		if(bs.equals(HttpHelp.CONNECTION_TIME_OUT)){
			EXCEPTION_MSG = ExceptionMsg.CONNECT_TIME_OUT_ERR;
			throw new Exception();
		}
		else if(bs.equals(HttpHelp.NO_SUCH_METHOD)){
			EXCEPTION_MSG = ExceptionMsg.NO_INTERFACE_METHOD_ERR;
			throw new Exception();
		}
		else if(bs.equals(HttpHelp.INTERFACE_ERR)){
			EXCEPTION_MSG = ExceptionMsg.INTERFACE_ERR;
			throw new Exception();
		}
	}

	public static void quitApplication(Context con){
		try{
			for(Activity a:fp.getAlist()){
				if(a!=null){
					a.finish();
				}
			}
			Intent serviceIntent = new Intent(MainService.Name);
			con.stopService(serviceIntent);
			ActivityManager activityManager =
					(ActivityManager) con.getSystemService(Context.ACTIVITY_SERVICE);
			activityManager.restartPackage(FrameParam.packageName);
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			System.exit(0);
		}
	}

	//判断后台服务有无开启
	public static boolean isServiceRunning(Context mContext,String className) { 
		boolean isRunning = false; 
		ActivityManager activityManager = (ActivityManager) 
				mContext.getSystemService(Context.ACTIVITY_SERVICE);  
		List<ActivityManager.RunningServiceInfo> serviceList  
		= activityManager.getRunningServices(30); 
		if (!(serviceList.size()>0)) { 
			return false; 
		} 
		for (int i=0; i<serviceList.size(); i++) { 
			if (serviceList.get(i).service.getClassName().equals(className) == true) { 
				isRunning = true; 
				break; 
			} 
		} 
		return isRunning; 
	}

	public static boolean chechbs_isinnormal(String bs)
	{
		if(bs.startsWith(HttpUtil.CONNECTION_TIME_OUT)||bs.startsWith(HttpUtil.INTERFACE_ERR)||bs.startsWith(HttpUtil.NO_SUCH_METHOD)){
			return true;
		}
		else{
			return false;
		}
	}
}